<template>
  <div>
    <Portal to="right-disable"
            :disabled="!queryModelDefaultSetting.showSetting">
      <div class='dropdown'>
        <el-card shadow="hover"
                 v-if="gadgetSetting.show">
          <p style='margin-bottom: 10px;'>
            <span v-if='"" !== gadgetSetting.name'
                  style='font-size:16px; font-weight: 600'>{{ gadgetSetting.name }}</span>
            <el-tooltip :open-delay="1000" class="item"
                        effect="dark"
                        :content="gadgetSetting.description"
                        placement="right"
                        v-if='"" !== gadgetSetting.description'>
              <i class="cuifont icon_help_circle"
                 style='margin-left:5px;'></i>
            </el-tooltip>
          </p>
          <div class=control-section>
            <div class=content-wrapper
                 v-loading="loading"
                 style="width:100%">
              <div class="contant_filter">
                <div class="filter_label">{{gadgetSetting.filterlabel}}</div>
                <el-cascader style="width:100%;flex:1"
                  v-model="value" filterable clearable
                  :options="options"
                  :props="{ expandTrigger: 'hover',label:gadgetSetting.text,value:gadgetSetting.value }"
                  @change="onchange"></el-cascader>
              </div>
           </div>
          </div>
        </el-card>
        <div class=control-section
             :style="{height: gadgetHeight + 'px'}"
             v-else>
          <div class=content-wrapper
               v-loading="loading"
               style="width:100%;">
            <div class="contant_filter">
                <div class="filter_label">{{gadgetSetting.filterlabel}}</div>
                <el-cascader style="width:100%;flex:1"
                  v-model="value" filterable clearable
                  :options="options"
                  :props="{ expandTrigger: 'hover',label:gadgetSetting.text,value:gadgetSetting.value }"
                  @change="onchange"></el-cascader>
            </div>
          </div>
        </div>
      </div>
    </Portal>
    <model :showSetting="queryModelDefaultSetting.showSetting"
           @queryModelClosed="queryModelClosed"
           @queryModelPreview="queryModelPreview"
           :dataInfo="queryModelDefaultSetting.dataInfo"
           :updateGadget="upgradeGadgetSetting"
           :slicer='slicer' />
  </div>
</template>

<script>
import mixinGadgetViewModule from '@/mixins/gadget-view-module'
// import model from '@/components/gadget/query-model/query-model.vue'
import { getUrlQureyParams } from '@/utils/common'
import { defaultGadgetSettingList } from '@/utils/data-json'
import { debounce } from 'lodash'
import { sqlSet } from '@/components/storybook/utilties/throttleRequest'
export default ({
  mixins: [mixinGadgetViewModule],
  components: { model: () => import('@/components/gadget/query-model/query-model') },
  data: function () {
    return {
      datesource: {
        value: '100',
        text: '100'
      },
      options: [],
      gadgetSetting: {},
      value: null,
      gadgetStatus: 'init',
      loading: false,
      queryModelDefaultSetting: {
        showSetting: false,
        dataInfo: {
          businessId: this.pageId,
          gadgetId: this.id,
          gadgetSettingExclude: ['DATA'],
          gadgetType: 'cascadergadget',
          gadgetSetting: this._.find(defaultGadgetSettingList, { gadgetType: 'cascadergadget' }).gadgetSetting
          // gadgetSetting: {
          //   showClearButton: 'true',
          //   watermark: 'Select a Client',
          //   allowFiltering: true,
          //   filterPlaceholder: 'Search',
          //   fields: { text: 'text', value: 'value' },
          //   height: '220px',
          //   queryParams: 'tenantCode',
          //   show: false,
          //   name: '',
          //   description: ''
          // }
        }
      },
      heightoffset: 60

    }
  },
  beforeCreate () {
    // this.$options.components.model = () => import('@/components/gadget/query-model/query-model')
  },
  created () {
    this.query()
    this.$store.state.isWidget = false
    this.gadgetHeight = this.gadgetInfo.h * 20 - this.heightoffset - 36
  },
  activated () {
    this.afterQuery()
  },
  resized (i, newH, newW, newHPx, newWPx) {
    this.gadgetHeight = newH * 20 - this.heightoffset - 36
  },
  destroyed () {
    this.delQueryParam()
  },
  methods: {
    queryModelClosed () {
      this.queryModelDefaultSetting.showSetting = false
      this.query()
    },
    showQueryModel () {
      this.queryModelDefaultSetting.showSetting = true
    },
    query () {
      this.loading = true
      this._.merge(this.gadgetSetting, this.queryModelDefaultSetting.dataInfo.gadgetSetting)
      var _self = this
      var param = {
        pageId: this.pageId,
        gadgetId: this.id,
        code: this.code,
        gadgettype: this.wgadgettype,
        widgetName: this.wName
      }
      this.$interface.reports.getReportDataInfo(param).then(({ data: res }) => {
        if (res.config) {
          _self._.merge(_self.gadgetSetting, res.config)
        }
        if (res.data) {
          var tempList = []
          if (!_self.gadgetSetting.associatedFields[0].value) {
            this.loading = false
            return
          }
          tempList = this._.uniqBy(JSON.parse(JSON.stringify(res.data)), _self.gadgetSetting.associatedFields[0].value)
          tempList.forEach((item, index) => {
            item[_self.gadgetSetting.text] = item[_self.gadgetSetting.associatedFields[0].value]
            item.children = res.data.filter(i => {
              return i[_self.gadgetSetting.associatedFields[0].value] === item[_self.gadgetSetting.associatedFields[0].value]
            })
          })
          if (_self.gadgetSetting.associatedFields[1]) {
            tempList.forEach(item => {
              var arr = this._.uniqBy(JSON.parse(JSON.stringify(item.children)), _self.gadgetSetting.associatedFields[1].value)
              arr.forEach((its, index) => {
                its[_self.gadgetSetting.text] = its[_self.gadgetSetting.associatedFields[1].value]
                its.children = res.data.filter(i => {
                  return i[_self.gadgetSetting.associatedFields[1].value] === its[_self.gadgetSetting.associatedFields[1].value]
                })
              })
              item.children = arr
            })
          }
          _self.options = tempList
        }
        _self.afterQuery()
        // _self.updateGadgetStatus('ready') //! IMPORTANT must have this code in every gadget
        this.loading = false
      }).catch(() => {
        this.loading = false
      }).finally(() => {
        this.loading = false
        this.updateGadgetLoadingStatus(!this.loading)
      })
    },
    afterQuery () {
      var valueFromQuery = getUrlQureyParams(this.gadgetSetting.queryParams)
      if (valueFromQuery) {
        this.value = valueFromQuery
      } else {
        var saveSlicer = localStorage.getItem(this.pageId + '-dropdown-list-gadget-' + this.gadgetSetting.queryParams)
        if (saveSlicer) {
          this.value = JSON.parse(saveSlicer)
          valueFromQuery = JSON.parse(saveSlicer)
        } else {
          if (this.gadgetSetting.associatedFields.length === 2) {
            this.value = this.options[0].children[0].children[0][this.gadgetSetting.value]
            valueFromQuery = this.options[0].children[0].children[0][this.gadgetSetting.value]
          } else if (this.gadgetSetting.associatedFields.length === 1) {
            this.value = this.options[0].children[0][this.gadgetSetting.value]
            valueFromQuery = this.options[0].children[0][this.gadgetSetting.value]
          }
        }
      }
      this.getDataListParams(valueFromQuery)
    },
    onchange (e) {
      this.getDataListParams(e)// e.itemData.value
    },
    onFiltering (e) {
      // get input data

    },
    getDataListParams (val) {
      if (Array.isArray(val)) {
        val = val[val.length - 1]
      }
      var _self = this
      if (val) {
        sqlSet.clear()
        var newslicer = {}
        newslicer[_self.gadgetSetting.queryParams] = val
        _self._.merge(_self.slicer, newslicer)
        localStorage.setItem(this.pageId + '-dropdown-list-gadget-' + _self.gadgetSetting.queryParams, JSON.stringify(val))
      } else {
        delete _self._.merge(_self.slicer, newslicer)
        localStorage.removeItem(this.pageId + '-dropdown-list-gadget-' + _self.gadgetSetting.queryParams)
        this.$message.error(this.gadgetSetting.watermark)
      }
      _self.updateGadgetStatus('ready')
    },
    activedAfterQuery: debounce(function () {
      var _self = this
      _self.updateGadgetStatus('ready')
    }, 0),
    delQueryParam () {
      delete this.slicer[this.gadgetSetting.queryParams]
    }
  }
})
</script>
<style scoped lang="scss">
.contant_filter {
  display: flex;
  align-items: center;
  .filter_label {
    margin-right: 10px;
  }
}

</style>
